package com.bestcem.xm.award.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.bestcem.xm.award.config.WxConfig;
import com.bestcem.xm.award.constant.RedPacketConstant;
import com.bestcem.xm.award.service.WxService;
import com.bestcem.xm.award.service.dto.wx.WxAccessTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author xa.zhang <xa.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/7/20 11:11
 * @desc
 */
@Slf4j
@Service
public class WxServiceImpl implements WxService {

    @Resource
    private WxConfig wxConfig;

    /**
     * 请求AccessTokenUrl
     * @param code 微信code
     * @return 结果
     */
    @Override
    public WxAccessTokenResponse requestAccessToken(String code) {
        String url = wxConfig.getAccessTokenUrl();

        url = String.format(url, wxConfig.getAppId(), wxConfig.getSecret(), code);

        String result = HttpUtil.get(url, RedPacketConstant.WX_REQUEST_TIMEOUT);
        if (StringUtils.isNotBlank(result)) {
            return JSON.parseObject(result, WxAccessTokenResponse.class);
        }

        return null;
    }
}
